package com.garbuz.svnadmin.view.common
{
	import actionlib.common.events.EventSender;

	import flash.display.DisplayObject;
	import flash.events.KeyboardEvent;
	import flash.ui.Keyboard;

	import mx.containers.TitleWindow;
	import mx.core.Application;
	import mx.events.FlexEvent;
	import mx.managers.IFocusManagerComponent;
	import mx.managers.PopUpManager;

	public class PopUpBase extends TitleWindow
	{
		[Bindable]
		public var focusedControl:IFocusManagerComponent;

		private var _closeEvent:EventSender = new EventSender(this);

		public function PopUpBase()
		{
			addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
			addEventListener(FlexEvent.CREATION_COMPLETE, onCreationComplete);
		}

		private function onCreationComplete(event:FlexEvent):void
		{
			if (focusedControl)
				focusManager.setFocus(focusedControl);
			else if (defaultButton is IFocusManagerComponent)
				focusManager.setFocus(IFocusManagerComponent(defaultButton));

			onInitialize();
		}

		protected function onInitialize():void
		{
		}

		private function onKeyDown(event:KeyboardEvent):void
		{
			if (event.charCode == Keyboard.ESCAPE)
				close();
		}

		public function onClose(handler:Function):PopUpBase
		{
			closeEvent.addListener(handler);
			return this;
		}

		public function close():void
		{
			_closeEvent.dispatch();
			PopUpManager.removePopUp(this);
		}

		public function show(parent:DisplayObject = null):void
		{
			PopUpManager.addPopUp(this, parent || DisplayObject(Application.application), true);
			PopUpManager.centerPopUp(this);
		}

		public function get closeEvent():EventSender
		{
			return _closeEvent;
		}
	}
}
